package com.flymobi.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.flymobi.fw.modules.CommonService;
import com.flymobi.fw.util.DateUtil;
import com.flymobi.fw.util.MyQueue;
import com.flymobi.po.ViewLog;
import com.flymobi.util.C;
import com.flymobi.util.QL;

public class ViewLogService extends CommonService {

	public List<ViewLog> list(int startRow, int pagePerSize) {
		return dao.find(ViewLog.class, QL.HQL.ViewLog.LIST, new Object[] {},startRow, pagePerSize);
	}
	
	public Long getCount() {
		return dao.getCount(QL.HQL.ViewLog.GET_COUNT, new Object[] {});
	}
	
	public void logFile(ViewLog vo) {
		if(vo!=null){ 
			int id=0; 
			id=new Random().nextInt(10);
			String day = DateUtil.dateFormate(new Date(), "HH");
			String day2 = DateUtil.dateFormate(new Date(), "yyyyMMdd");
			File dir=new File(C.UPLOAD_FILE_PATH+"/"+day2);
			if(!dir.exists()){
				dir.mkdirs();
			}
			File f=new File(C.UPLOAD_FILE_PATH+"/"+day2+"/"+day+id+".viewlog");
			BufferedWriter br=null;
			try {
				br = new BufferedWriter(new FileWriter(f,true));
					br.write(vo.toString()+"\n");
				br.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				try {
					if(br!=null){
						br.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void save(MyQueue<ViewLog> queue) {
		if(queue==null){
			return ;
		}
		int count=queue.size();
		if(count>=1){
			for(int i=0;i<count;i++){
				ViewLog vo=queue.dequeue();
				dao.save(vo);
			}
		}
	}

	public void save(ViewLog ViewLog) {
		dao.save(ViewLog);
	}

	public ViewLog load(String id) {
		return dao.load(ViewLog.class, new Long(id));
	}
	
	public ViewLog get(String id) {
		return dao.get(ViewLog.class, new Long(id));
	}

	public void delete(String id) {
		dao.delete(this.get(id));
	}
	
	public static void main(String[] args){
		while(true){
			System.out.println("start:"+new Date());
			String day = DateUtil.dateFormate(new Date(), "MMddHH");
			File f=new File(C.UPLOAD_FILE_PATH+"/"+day+".viewlog");
			BufferedWriter br=null;
			try {
				br = new BufferedWriter(new FileWriter(f,true));
				for(int i=0;i<10;i++){
					ViewLog vo=new ViewLog();
					vo.setSavetime(new Date());
					vo.setUpdatetime(new Date());
					br.write(vo.toString()+"\n");
				}
				br.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				try {
					if(br!=null){
						br.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println("end:"+new Date());
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
